package com.foreverwin.jzymes.framework.quartz.service.impl;


import com.foreverwin.jzymes.framework.quartz.constant.ScheduleConstants;
import com.foreverwin.jzymes.framework.quartz.domain.SysJob;
import com.foreverwin.jzymes.framework.quartz.domain.SysJobParam;
import com.foreverwin.jzymes.framework.quartz.mapper.SysJobMapper;
import com.foreverwin.jzymes.framework.quartz.mapper.SysJobParamMapper;
import com.foreverwin.jzymes.framework.quartz.service.ISysJobScheduleService;
import com.foreverwin.jzymes.framework.quartz.util.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysJobScheduleServiceImpl implements ISysJobScheduleService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper jobMapper;

    @Autowired
    private SysJobParamMapper jobParamMapper;

    @Value("${mes.quartz.enable}")
    boolean enable = true;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init()
    {
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList)
        {
            setUpJobParam( job );

            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, job.getHandle());
            // 如果不存在，则创建
            if (cronTrigger == null)
            {
                ScheduleUtils.createScheduleJob(scheduler, job);
            }
            else
            {
                ScheduleUtils.updateScheduleJob(scheduler, job);
            }
        }
    }

    /*@PreDestroy
    public void destroy(){
        if( scheduler != null ){
            try{
                if( scheduler.isStarted() ){
                    scheduler.shutdown( true );
                }
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    }*/

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    public int pauseJob(SysJob job)
    {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateSysJob(job);
        if (rows > 0)
        {
            ScheduleUtils.pauseJob(scheduler, job.getHandle());
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    public int resumeJob(SysJob job)
    {
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateSysJob(job);
        if (rows > 0)
        {
            ScheduleUtils.resumeJob(scheduler, job.getHandle());
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    public int deleteJob(SysJob job)
    {
        int rows = jobMapper.deleteSysJobById(job);
        if (rows > 0)
        {
            ScheduleUtils.deleteScheduleJob(scheduler, job.getHandle());
        }
        return rows;
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    public int changeStatus(SysJob job)
    {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
        {
            rows = resumeJob(job);
        }
        else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
        {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    public int run(SysJob job)
    {
        setUpJobParam( job );
        return ScheduleUtils.run(scheduler, jobMapper.selectSysJobById(job.getHandle()));
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    public int insertJobCron(SysJob job)
    {
        setUpJobParam( job );

        //job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertSysJob(job);
        if (rows > 0)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    public int updateJobCron(SysJob job)
    {
        setUpJobParam( job );

        int rows = jobMapper.updateSysJob(job);
        if (rows > 0)
        {
            ScheduleUtils.updateScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 设置任务参数
     *
     * @param job
     */
    public void setUpJobParam( SysJob job ){
        SysJobParam queryParam = new SysJobParam();
        queryParam.setJobBo( job.getHandle() );
        List<SysJobParam> jobParamList = jobParamMapper.selectSysJobParamList( queryParam );
        Map<String,String> jobParamMap = new HashMap<>();
        for( SysJobParam jobParam : jobParamList ){
            jobParamMap.put( jobParam.getParamName(), jobParam.getParamValue() );
        }
        job.setJobParamMap( jobParamMap );
    }
}
